let context;
try {
  context = browser;
} catch (error) {
  console.error(error);
  try {
    context = chrome;
  } catch (error) {
    console.error(error);
  }
}

// 防抖函数
function debounce(func, wait) {
  let timeout;
  return function () {
    const context = this,
      args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
  };
}

// 监听元素添加的函数
function observeElementAddition(selector, callback) {
  const observer = new MutationObserver(
    debounce((mutations) => {
      callback();
    }, 200)
  ); // 200ms的防抖时间

  // 开始观察目标元素
  observer.observe(document.body, { childList: true, subtree: true });
}

observeElementAddition(".annotation_item", () => {
  searchAll();
});

let data = {};
let composeCode = "";
function searchAll() {
  //查找所有元素 .annotation_item
  var elements = document.querySelectorAll(".annotation_item");
  data = {};
  let layoutInfo = {};
  let textInfo = {};
  let colorInfo = {};
  for (var i = 0; i < elements.length; i++) {
    let el = elements[i];
    /**
     * {"layerName":"Rectangle 5376","positions":["16dp","104dp","343dp","40dp"],
     * "sizes":["343dp","40dp"],"opacity":"100%","borderRadius":"8dp  8dp  8dp  8dp"}
     */
    let info = {};
    info = extractElementInfo(el);
    // console.log("info", info);
    if (info.layerName) {
      layoutInfo = info;
    }

    //{"colorStyle":"主色/Cupid","colorValue":"#FF5E8BFF","colorType":"HEXA"}
    //{"colors":[{"rgb":"rgb(255, 83, 188)","hex":"#FFFF53BC","style":"AHEX"},{"rgb":"rgb(255, 147, 213)","hex":"#FFFF93D5","style":"AHEX"}]}
    info = parseColorItem(el);
    if (info.colors.length > 0) {
      colorInfo = info;
      console.log("parse color ==>", JSON.stringify(info));
    }

    //{"font":"D-DIN-DIN-Bold","fontWeight":"Bold","align":"左对齐","color":"#1D2129FF","fontSize":"32sp",
    //"letterSpacing":"0dp","lineHeight":"32dp","content":"32dp"}
    info = extractTextInfo(el);
    if (info.fontWeight && info.lineHeight) {
      textInfo = info;
    }
  }
  console.log("searchall", layoutInfo, textInfo, colorInfo);
  if (textInfo.fontWeight && textInfo.lineHeight) {
    let fontWeight =
      textInfo.fontWeight === "Bold" ? "fontWeight=FontWeight.Bold," : "";
    if (textInfo.fontWeight === "Medium") {
      fontWeight = "fontWeight=FontWeight.Medium";
    }
    if (fontWeight !== "") {
      fontWeight = `,${fontWeight}`;
    }
    let fontSizeStr = `,fontSize=${textInfo.fontSize.replace("sp", "")}.sp`;
    composeCode = `Text(text="${
      layoutInfo.layerName
    }",color=Color(0x${textInfo.color.replace(
      "#",
      ""
    )})${fontSizeStr}${fontWeight})`;
  } else {
    if (layoutInfo.layerName) {
      let sizes = layoutInfo.sizes || [];
      let sizeStr = "";
      if (sizes.length === 2) {
        sizeStr = `.size(${sizes[0].replace("dp", "")}.dp,${sizes[1].replace(
          "dp",
          ""
        )}.dp)`;
      }
      let dps = parseDp(layoutInfo.borderRadius);
      let shapeStr = "";
      if (Array.isArray(dps)) {
        shapeStr = `shape = RoundedCornerShape(${dps[0]}.dp,${dps[1]}.dp,${dps[2]}.dp,${dps[3]}.dp)`;
      } else {
        shapeStr = dps > 0 ? `shape = RoundedCornerShape(${dps}.dp)` : "";
      }
      let bgStr =
        colorInfo.colors.length === 0
          ? ""
          : `.background(${convertColorToCompose(colorInfo)},${shapeStr})`;
      composeCode = `Box(modifier=Modifier${sizeStr}${bgStr})`;
    }
  }
}

function convertColorToCompose(colorInfo) {
  //{"colors":[{"rgb":"rgb(255, 83, 188)","hex":"#FFFF53BC","style":"AHEX"},{"rgb":"rgb(255, 147, 213)","hex":"#FFFF93D5","style":"AHEX"}]}
  if (colorInfo.colors.length > 0) {
    if (colorInfo.colors.length === 1) {
      return `color=Color(0x${colorInfo.colors[0].hex.replace("#", "")})`;
    } else {
      let colors = colorInfo.colors.map(
        (item) => `Color(0x${item.hex.replace("#", "")})`
      );
      return `Brush.verticalGradient(colors = listOf(${colors.join(",")}))`;
    }
  } else {
    return `color=Color.BLACK`;
  }
}

function parseDp(paddingString) {
  if (!paddingString) {
    return 0;
  }
  // 使用不定长空格分割字符串
  const paddingArray = paddingString.split(/\s+/);

  console.log(paddingString, "====>", paddingArray);

  // 检查所有元素是否都相同
  const allEqual = paddingArray.every((element) => element === paddingArray[0]);

  if (allEqual) {
    // 如果所有元素都相同，返回一个字符串
    return parseInt(paddingArray[0].replace("dp", ""));
  } else {
    // 如果元素不同，返回一个去除"dp"的数字数组
    return paddingArray.map((element) => parseInt(element.replace("dp", "")));
  }
}

function parseAnnotationItem(tempDiv) {
  // 创建一个对象来存储解析后的信息
  const annotationItem = {};

  // 获取并设置图层名称
  const layerNameElement = tempDiv.querySelector(".layer_name");
  annotationItem.layerName = layerNameElement
    ? layerNameElement.textContent
    : "";

  // 获取并设置位置
  const positionElements = tempDiv.querySelectorAll(".two");
  annotationItem.position = Array.from(positionElements).map(
    (element) => element.textContent
  );

  // 获取并设置大小
  const sizeElements = tempDiv.querySelectorAll(".copy_text");
  annotationItem.size = Array.from(sizeElements)
    .slice(0, 2)
    .map((element) => element.textContent);

  // 获取并设置不透明度
  const opacityElement = tempDiv.querySelector(".item_one .copy_text");
  annotationItem.opacity = opacityElement ? opacityElement.textContent : "";

  // 获取并设置圆角
  const cornerRadiusElement = tempDiv.querySelector(".copy_text");
  annotationItem.cornerRadius = cornerRadiusElement
    ? cornerRadiusElement.textContent
    : "";

  // 返回解析后的对象
  return annotationItem;
}

chrome.runtime.onMessage.addListener((message, sender, callback) => {
  if (message.action === "show") {
    console.log("show==>", composeCode);
    callback(composeCode);
    // callback(data);
  }
});

document.addEventListener("DOMContentLoaded", function () {
  searchAll();
});

function showData(data) {}

/**
 * 监听元素添加bingfangdou
 * @param {*} element
 * @returns
 */

function extractElementInfo(element) {
  // 检查元素是否存在
  if (!element) {
    return null;
  }

  // 查找关键信息
  const layerNameElement = element.querySelector(".layer_name_wrap");
  const positionElements = element.querySelectorAll(".item_two .two");
  const sizeElements = element.querySelectorAll(".item_two .two .copy_text");
  const opacityElement = element.querySelector(".item_one .copy_text");
  const borderRadiusElement = element.querySelector(
    "div.copy_text.item_one > span"
  );

  // 提取信息
  const layerName = layerNameElement
    ? layerNameElement.textContent.trim()
    : null;
  const positions = Array.from(positionElements).map((el) =>
    el.textContent.trim()
  );
  const sizes = Array.from(sizeElements).map((el) => el.textContent.trim());
  const opacity = opacityElement ? opacityElement.textContent.trim() : null;
  const borderRadius = borderRadiusElement
    ? borderRadiusElement.textContent.trim()
    : null;

  // 返回信息对象
  return {
    layerName,
    positions,
    sizes,
    opacity,
    borderRadius,
  };
}

function parseColorItem(tempDiv) {
  // 创建一个对象来存储解析后的信息
  const colorItem = {};

  // 获取并设置颜色列表
  const colorElements = tempDiv.querySelectorAll(".color_li");
  colorItem.colors = Array.from(colorElements).map((element) => {
    const color = {};
    const colorElement = element.querySelector(".color");
    const colorItemElement = element.querySelector(".color_item .copy_text");
    const colorStyleElement = element.querySelector(".color_style");
    color.rgb = colorElement ? colorElement.style.backgroundColor : "";
    color.hex = colorItemElement ? colorItemElement.textContent : "";
    color.style = colorStyleElement ? colorStyleElement.textContent : "";
    return color;
  });

  // 返回解析后的对象
  return colorItem;
}

function extractColorInfo(element) {
  // 检查元素是否存在
  if (!element) {
    return null;
  }

  // 查找关键信息
  const colorStyleElement = element.querySelector(".item_content.copy_text");
  const colorValueElement = element.querySelectorAll(".color_item .copy_text");
  const colorTypeElement = element.querySelector(".color_style");

  //遍历colorValueElement, 获取颜色值
  let colors = [];
  if (colorValueElement) {
    colorValueElement.forEach((el) => {
      colors.push(el.textContent.trim());
    });
  }
  console.log("colors==>", colorValueElement);
  // 提取信息
  const colorStyle = colorStyleElement
    ? colorStyleElement.textContent.trim()
    : null;
  const colorValue = colorValueElement ? colors : [];
  const colorType = colorTypeElement
    ? colorTypeElement.textContent.trim()
    : null;

  // 返回信息对象
  return {
    colorStyle,
    colorValue,
    colorType,
  };
}

function extractTextInfo(element) {
  // 检查元素是否存在
  if (!element) {
    return null;
  }

  // 查找关键信息
  const fontElement = element.querySelector(".layer_name");
  const fontWeightElement = element.querySelector(".item_one");
  const alignElement = element.querySelector(".align_text");
  const colorElement = element.querySelector(".color_item .copy_text");
  const fontSizeElement = element.querySelector(".two .copy_text");
  const letterSpacingElement = element.querySelector(
    ".space_wrap .two .copy_text"
  );
  const lineHeightElement = element.querySelector(
    ".item_content .two .copy_text"
  );
  const contentElement = element.querySelector(".item_content .copy_text");

  // 提取信息
  const font = fontElement ? fontElement.textContent.trim() : null;
  const fontWeight = fontWeightElement
    ? fontWeightElement.textContent.trim()
    : null;
  const align = alignElement ? alignElement.textContent.trim() : null;
  const color = colorElement ? colorElement.textContent.trim() : null;
  const fontSize = fontSizeElement ? fontSizeElement.textContent.trim() : null;
  const letterSpacing = letterSpacingElement
    ? letterSpacingElement.textContent.trim()
    : null;
  const lineHeight = lineHeightElement
    ? lineHeightElement.textContent.trim()
    : null;
  const content = contentElement ? contentElement.textContent.trim() : null;

  // 返回信息对象
  return {
    font,
    fontWeight,
    align,
    color,
    fontSize,
    letterSpacing,
    lineHeight,
    content,
  };
}
